package Operation;

import Book.Book;
import Book.Bookshelf;

import java.util.Scanner;

public class deleteBookOperate implements IOOperation{
    public void work(Bookshelf bookshelf) {

        System.out.println("删除图书........");
        System.out.println("请输入你要删除的图书：");
        Scanner s = new Scanner(System.in);
        String name = s.nextLine();
        Book[] books = bookshelf.getBookList();
        Boolean isBook = false;
        int pos = -1;
        //判断图书是否存在
        for (int i = 0; i < bookshelf.getUsedSize(); i++) {
            if(name.equals(books[i].getName())) {
                isBook = true;
                pos = i;
            }
        }
        //不存在
        if(isBook==false) {
            System.out.println("删除图书失败。"+"馆里还没有这本 "+name+" 书");
        } else {
            //如果为最后一本图书，特判，直接置为null
            if(pos==bookshelf.getUsedSize()-1) {
                books[pos] = null;
            }
            else{
                //不是最后一本，则按这种算法
                for (int i = pos; i < bookshelf.getUsedSize()-1; i++) {
                    if(name.equals(books[i].getName())) {
                        books[i] = books[i+1];
                    }
                }
            }
            //最后修改使用的大小
            bookshelf.setUsedSize(bookshelf.getUsedSize()-1);
        }

    }
}
